<?php

class httpUnit{
	public static function json($url, $post_data=array(), $signkey='', $cookiefile=''){

		$data = self::post($url, $post_data, $signkey, $cookiefile);
		if($data['httpcode']!=200){
			$errStr = "通信失败，请稍后再试";
		}else{
			$result = json_decode($data['html'], true);
			if(!is_array($result)){
				$errStr = "接口通信错误！";
				if($GLOBALS['debug']){
					$errStr .= "<p>".var_dump($data)."</p>";
				}
			}elseif($result['status']!=1){
				$errStr = $result['errMsg'];
			}
		}
		if(!empty($errStr)){
			$is_sign_error = isset($result['errType']) && in_array($result['errType'], array('appIdError', 'domainError', 'signError', 'checkError') ) ? true : false ;
			if(IS_AJAX){
				if( $is_sign_error && defined('APPNAME') ){
					controller::json( array('status' => $result['status'], 'errMsg' => $result['errMsg'], 'redirect' => '?m=system&a=bind') );
				}else{
					controller::json( $result );
				}
			}else{
				if( $is_sign_error && defined('APPNAME') ){
					controller::redirect('?m=system&a=bind', $result['errMsg']);
				}else{
					controller::page_503();
					throw new Exception($result['errMsg']);
				} 
			}
		}
		return $result;
	}

	public static function get($url){
		return self::post($url);
	}

	public static function post($url, $post_data=array(), $signkey='', $cookiefile=''){
		if(!empty($post_data)){
			$post_method = 'POST';
			$post_type = 1;
		}else{
			$post_method = 'GET';
			$post_type = 0;
		}
		if(!empty($signkey)){
			$post_data['sign'] = self::sign($post_data, $signkey);
		}
		$ch = curl_init();
		if(!empty($cookiefile)){
			if(is_array($cookiefile)){
				curl_setopt($ch, CURLOPT_COOKIE, str_replace('&', ';', http_build_query($cookiefile)));
			}else{
				$cookie_jar = DATA.'/temp/cookie_'.$cookiefile.'.inc';
				curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
				curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
			}
		}
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		curl_setopt($ch, CURLOPT_USERAGENT, self::userAgent());
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $post_method);
		curl_setopt($ch, CURLOPT_REFERER, self::get_referer($url) );
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, $post_type);
		if(!empty($post_data)){
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data) );
		}
		curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
		curl_setopt($ch, CURLOPT_HEADER, 1);
		curl_setopt($ch, CURLOPT_NOSIGNAL,1);

		if(strpos($url, 'https://')!==false){
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
			curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
			curl_setopt($ch, CURLOPT_CAINFO, DATA.'/resource/cacert.pem');
		}

		defined('CURLOPT_TIMEOUT_MS') && curl_setopt($ch, CURLOPT_TIMEOUT_MS, 60000);
		$result = curl_exec($ch);
		if($result !== false) {
			$return['httpcode'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			$return['charset'] = self::get_charset( curl_getinfo($ch, CURLINFO_CONTENT_TYPE) );
			$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
			$return['header'] = substr($result, 0, $headerSize);
			$return['html'] = substr($result, $headerSize);
			if($return['httpcode']=="301" || $return['httpcode']=="302"){
				if(preg_match("#Location: (.*)#", $return['header'], $mt)){
					$mt[1] = str_replace('news.sogou.com', 'www.sogou.com', $mt[1]);
					return self::post(trim($mt[1]), $post_data, $signkey, $cookiefile);
				}
			}
		}else{
			$err = curl_error($ch);
			$return['httpcode'] = 0;
			$return['errMsg'] = $err;
		}
		curl_close($ch);
		return $return;
	}
	
	public static function sign_check($signkey){
		while (list ($key, $val) = each ($_REQUEST)) {
			if($key == "sign" || $key == "m" || $key == "a") continue;
			else $para[$key] = stripslashes($val);
		}

		ksort($para);
		reset($para);

		$arg  = "";
		while (list ($key, $val) = each ($para)) {
			$arg.=$key."=".$val."&";
		}
		$arg = substr($arg,0,count($arg)-2);
		$sign = md5($arg.$signkey);

		if($sign == $_REQUEST["sign"]){
			return true;
		}
		return false;
	}

	private static function sign($para=array(), $signkey){
		ksort($para);
		reset($para);

		$arg  = "";
		while (list ($key, $val) = each ($para)) {
			if($key == "sign" || $key == "m" || $key == "a") continue;
			$arg.=$key."=".$val."&";
		}
		$arg = substr($arg,0,count($arg)-2);
		return md5($arg.$signkey);
	}

	private static function userAgent(){
		if(isset($_SERVER['HTTP_USER_AGENT'])){
			$user_agent = $_SERVER['HTTP_USER_AGENT'];
		}else{
			$user_agent = "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)";
		}
		return $user_agent;
	}
	private static function get_charset($string){
		if($string){
			if(preg_match("#charset=(gb2312|gbk|utf-8)#si", $string, $mt)){
				return strtolower( $mt[1] );
			}
			if(preg_match("#charset=\"(gb2312|gbk|utf-8)\"#si", $string, $mt)){
				return strtolower( $mt[1] );
			}
		}
		return false;
	}
	private static function get_referer($url){
		$noReferer = array(
			'qpic.cn',
			'v4.cc',
			);
		$host = 'http://'.parse_url($url, PHP_URL_HOST);
		foreach ($noReferer as $key => $value) {
			if(strpos($host, $value)!==false){
				return null;
			}
		}
		return $host;
	}

}

